import { Message } from 'element-ui'
import AdminsApi from '@/api/admins'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userInfo: {},
  userId: localStorage.getItem('userId'),
  role: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USER: (state, info) => {
    state.userInfo = info
  },
  SET_USERID: (state, id) => {
    state.userId = id
  },
  SET_ROLE: (state, role) => {
    state.role = role
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      AdminsApi.login({ phone: username.trim(), pwd: password }).then(response => {
        if (response.token) {
          commit('SET_TOKEN', response.token)
          setToken(response.token)
          commit('SET_USERID', response._id)
          localStorage.setItem('userId', response._id)
          resolve()
        } else {
          Message.error('账号或密码输入错误，请重新输入')
          reject()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      AdminsApi.getInfo(state.userId).then(response => {
        if (!response) {
          reject('身份信息过期！请重新登录！')
        }
        commit('SET_ROLE', response.role)
        commit('SET_NAME', response.name)
        commit('SET_USER', response)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    commit('SET_ROLE', '')
    removeToken()
    localStorage.clear()
    resetRouter()
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
